package com.example.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 */
@Component
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationFilter.class);


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {

        /**
         * 说明用户以 JSON 的形式传递的参数
         */
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            //获取用户登录信息
            String username="";
            String password="";
            try {
                Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(),Map.class);
                username= map.getOrDefault("username","").trim();
                password= map.getOrDefault("password","").trim();
            } catch (IOException e) {
                log.error("捕捉到异常 username:{},password:{},message:{} {}, 异常栈信息:",username,password,e.getMessage(),e);
                e.printStackTrace();
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username,password);
            // Allow subclasses to set the "details" property
            setDetails(request,authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request,response);

    }



}
